/*
 *  convertion.cpp
 *  ElektroM
 *
 *  Created by Michael on 11.10.09.
 *  Copyright 2009 Artgruppe inc. All rights reserved.
 *
 */
#include "convertion.h"

Knots* convertRailwaysIntoGraphs(stationInfo* stations, int N)
{
    Knots* aOut=(Knots*)malloc(sizeof(Knots)*N);
    int nBefore=-1;
    /// memmory allocation and initialization
    for(int i=0; i<N; i++)
    {
	// I do not like that string here
	// it takes a lot of memory:
	//aOut[i]._aWhereToGo=(WhereToGo*)malloc(sizeof(WhereToGo)*4);
	aOut[i]._aWhereToGo=NULL;
	aOut[i]._nCountWhere=0;
    }
    for(int i=0; i<N; i++)
    {				
		// it must be equal to i:
		aOut[i]._nKnot=stations[i].nId-1;
		// maximum value:
		int nCount=aOut[i]._nCountWhere;
		//printf("Before nBefore\n");
		// memory allocation;
		if(aOut[i]._aWhereToGo==NULL){
		    int curCount=0;
		    if(nBefore!=-1)
			curCount++;
		    if(stations[i].nNext)
			curCount++;
		    if(stations[i].nNode)
			curCount++;
		    aOut[i]._aWhereToGo=(WhereToGo*)malloc(sizeof(WhereToGo)*curCount);
		}

		if(nBefore!=-1)
		{
			aOut[i]._aWhereToGo[nCount].knot=nBefore;
			aOut[i]._aWhereToGo[nCount++].weight=1;
		}
		
		//printf("Before Next\n");
		if(stations[i].nNext)
		{
			aOut[i]._aWhereToGo[nCount].knot=stations[i].nNext-1;
			aOut[i]._aWhereToGo[nCount++].weight=1;
			nBefore=i;
		}
		else
			nBefore=-1;
		
		//printf("Before nNode it's value is %d\n", stations[i].nNode);
		if(stations[i].nNode)
		{			
		    aOut[i]._aWhereToGo[nCount].knot=stations[i].nNode-1;
		    aOut[i]._aWhereToGo[nCount++].weight=1;
		    /// add the link to the other end:			
		    if(stations[i].nNode-1>N)
		    {
			printf("!!!!nNode is %d\n", stations[i].nNode-1);
			continue;
		    }
		    int nIndexLinkedStation=stations[i].nNode-1;

		    if(aOut[nIndexLinkedStation]._aWhereToGo==NULL)
		    {
			int curCount=1;
			// what do you want to do with that variable?
			//if(nBefore!=-1) // simply state that there is that thing.
			    curCount++;
			if(stations[nIndexLinkedStation].nNext)
			    curCount++;
			if(stations[nIndexLinkedStation].nNode)
			    curCount++;
			aOut[nIndexLinkedStation]._aWhereToGo=(WhereToGo*)malloc(sizeof(WhereToGo)*curCount);

		    }
		    int nCountOtherNode=aOut[nIndexLinkedStation]._nCountWhere;	

		    aOut[nIndexLinkedStation]._aWhereToGo[nCountOtherNode].knot=
			stations[i].nId-1;
		    aOut[nIndexLinkedStation]._aWhereToGo[nCountOtherNode++].weight=1;
		    ++(aOut[nIndexLinkedStation]._nCountWhere);
		}
		aOut[i]._nCountWhere=nCount;
    }	
	
    return aOut;
}
